<template>
  <div class="app-container">
    <el-row style="padding-bottom: 20px" v-if="useUserStore().userType === '1' || useUserStore().userType === '2'">
      <el-col :span="4">
        <el-card shadow="always"><span>账户余额：{{ mnyForm.balance }}</span></el-card>
      </el-col>
      <el-col :span="4" style="margin-left: 20px">
        <el-card shadow="always"><span>冻结金额：{{ mnyForm.frozen }}</span></el-card>
      </el-col>
      <el-col :span="4" style="margin-left: 20px">
        <el-card shadow="always"><span>已提现金额：{{ mnyForm.extractAmount }}</span></el-card>
      </el-col>
    </el-row>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="提现类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择提现类型" clearable>
          <el-option
              v-for="dict in withdrawal_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
              v-for="dict in t_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              v-show="dict.value !== '04' && dict.value !== '10' && dict.value !== '11' && dict.value !== '12'"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="useUserStore().userType === '1' || useUserStore().userType === '2'">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:textract:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:textract:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:textract:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="textractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="提现人" align="center" prop="userName"/>
      <el-table-column label="提现人类型" align="center" prop="userType">
        <template #default="scope">
          <dict-tag :options="t_extract_user_type" :value="scope.row.userType"/>
        </template>
      </el-table-column>
      <el-table-column label="提现金额" align="center" prop="amount"/>
      <el-table-column label="提交时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="提现类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="withdrawal_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="银行卡号" width="250" align="center" prop="bankcardNo"/>
      <el-table-column label="手机号" width="150" align="center" prop="bankcardPhone"/>
      <el-table-column label="支付宝号" width="150" align="center" prop="alipayAccount"/>
      <el-table-column label="状态" align="center" prop="status" fixed="right">
        <template #default="scope">
          <dict-tag :options="t_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="审核原因" align="center" prop="statusReason"/>
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"-->
          <!--                     :class="{'but-disabled': !(scope.row.status === '00' || scope.row.status === '03')}"-->
          <!--                     v-hasPermi="['system:textract:edit']">修改-->
          <!--          </el-button>-->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     :class="{'but-disabled': !(scope.row.status === '00' || scope.row.status === '03')}"
                     v-hasPermi="['system:textract:remove']">删除
          </el-button>
          <el-button link type="primary" icon="Select" @click="handleSubmitAudit(scope.row)"
                     :class="{'but-disabled': !(scope.row.status === '00' || scope.row.status === '03')}"
                     v-hasPermi="['system:textract:submit']">提交
          </el-button>
          <el-button link type="primary" icon="CloseBold" @click="handleCancelSubmit(scope.row)"
                     :class="{'but-disabled': !(scope.row.status === '01')}"
                     v-hasPermi="['system:textract:cancel']">撤回
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改提现列表对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="textractRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="提现金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入提现金额"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提现类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择提现类型">
                <el-option
                    v-for="dict in withdrawal_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type === 1">
            <el-form-item label="银行卡号" prop="bankcardNo">
              <el-input v-model="form.bankcardNo" placeholder="请输入银行卡号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type === 1">
            <el-form-item label="手机号" prop="bankcardPhone">
              <el-input v-model="form.bankcardPhone" placeholder="请输入银行卡绑定手机号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.type === 2">
            <el-form-item label="支付宝号" prop="alipayAccount">
              <el-input v-model="form.alipayAccount" placeholder="请输入支付宝号"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Textract">
import {
  listTextract,
  getTextract,
  delTextract,
  addTextract,
  updateTextract,
  getCurrentBalance,
  updateStatus
} from "@/api/system/textract";
import useUserStore from '@/store/modules/user'

const {proxy} = getCurrentInstance();
const {
  withdrawal_type,
  t_status,
  t_extract_user_type
} = proxy.useDict('withdrawal_type', 't_status', 't_extract_user_type');

const textractList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  mnyForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    mnyId: undefined,
    amount: undefined,
    type: undefined,
    alipayAccount: undefined,
    paymentCode: undefined,
    bankcardNo: undefined,
    bankcardPhone: undefined,
    status: undefined,
    statusReason: undefined,
  },
  rules: {
    amount: [
      {required: true, message: "提现金额不能为空", trigger: "blur"},
      {
        validator: (rule, value, callback) => {
          if (value > 0) {
            callback();
          } else {
            callback(new Error("金额必须大于0"));
          }
        },
        trigger: "blur"
      },
      {
        validator: (rule, value, callback) => {
          if (mnyForm.value.balance > value) {
            callback();
          } else {
            callback(new Error("余额不足"));
          }
        },
        trigger: "blur"
      }
    ],
    type: [
      {required: true, message: "提现类型不能为空", trigger: "change"}
    ],
    bankcardNo: [
      {required: true, message: "银行卡号不能为空", trigger: "blur"},
      {pattern: /^[0-9]{16,19}$/, message: "银行卡号必须为16-19个数字！", trigger: "blur"}
    ],
    bankcardPhone: [
      {required: true, message: "银行卡绑定手机号不能为空", trigger: "blur"},
      {
        validator: (rule, value, callback) => {
          const reg = /^[1][3-9]\d{9}$/;
          if (reg.test(value)) {
            callback();
          } else {
            callback(new Error("请输入有效的手机号"));
          }
        },
        trigger: "blur"
      }
    ],
    alipayAccount: [
      {required: true, message: "支付宝号不能为空", trigger: "blur"},
      {pattern: /^[a-zA-Z0-9]{6,30}$/, message: "支付宝号必须为6-30个字符，可以包含数字和字母！", trigger: "blur"}
    ],
    status: [
      {required: true, message: "状态不能为空", trigger: "change"}
    ],
  }
});

const {queryParams, form, rules, mnyForm} = toRefs(data);

/** 查询提现列表列表 */
function getList() {
  loading.value = true;
  listTextract(queryParams.value).then(response => {
    textractList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  if (useUserStore().userType === '1' || useUserStore().userType === '2') {
    getCurrentBalance().then(response => {
      mnyForm.value = response.data;
    });
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    extractId: undefined,
    mnyId: undefined,
    amount: undefined,
    type: undefined,
    alipayAccount: undefined,
    paymentCode: undefined,
    bankcardNo: undefined,
    bankcardPhone: undefined,
    status: undefined,
    statusReason: undefined,
    auditTime: undefined,
    auditor: undefined,
    ext1: undefined,
    ext2: undefined,
    ext3: undefined,
    state: undefined,
    createTime: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined
  };
  proxy.resetForm("textractRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.extractId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加提现列表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _extractId = row.extractId || ids.value
  getTextract(_extractId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改提现列表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["textractRef"].validate(valid => {
    if (valid) {
      if (form.value.extractId != null) {
        updateTextract(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTextract(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _extractIds = row.extractId || ids.value;
  proxy.$modal.confirm('是否确认删除提现列表编号为"' + _extractIds + '"的数据项？').then(function () {
    return delTextract(_extractIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function handleSubmitAudit(row) {
  const _extractIds = row.extractId || ids.value;
  proxy.$modal.confirm('是否确认提交提现审核，编号为"' + _extractIds + '"的数据项？').then(function () {
    row.status = "01";
    return updateStatus(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("提交成功");
  }).catch(() => {
  });
}

function handleCancelSubmit(row) {
  const _extractIds = row.extractId || ids.value;
  proxy.$modal.confirm('是否确认撤回提现审核，编号为"' + _extractIds + '"的数据项？').then(function () {
    row.status = "00";
    return updateStatus(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("撤回成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/textract/export', {
    ...queryParams.value
  }, `textract_${new Date().getTime()}.xlsx`)
}

onActivated(() => {
    getList();
})


getList();
</script>
